<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;
class AdmissionTicket extends Model
{
    // 门票费用（手牌模式使用）
    protected $name = 'qt_admission_ticket';
    protected $autoWriteTimestamp = true;


    /**
     * 新增门票费用
     * @param $engineerId
     */
    public static function admissionTicketPrice($handTypeId,$handCardId,$userInfo){
        $admissionTicketData = self::where("FIND_IN_SET(" . $handTypeId . ",hand_cards)")->where(['store_id'=>$userInfo['store_id']])->find();
        if(!empty($admissionTicketData)){
            $goodsIds = explode(',',$admissionTicketData['product_ids']);
            $roomId = $admissionTicketData['room_id'];
            $roomData = Db::name('qt_room')->where(['id'=>$roomId])->find();
            if($roomData['status_id'] == '1'){
                Db::name('qt_room')->where(['id'=>$roomId])->update(['status_id'=>'10']);
                //增加开房记录
                Db::name('qt_room_log')->insert(['room_id'=>$roomId,'user_id'=>$userInfo['id'],'created_time'=>time()]);
            }else{
                return ['status'=>false,'msg'=>"房间状态不正确，无法下单"];
            }
            $goodsOrder = Db::name('qt_product_order')->where(['room_id' => $roomId, 'order_status' => '0'])->find();
            $handGrandId = Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCardId,'status'=>'2'])->order('id desc')->value('id');
            foreach ($goodsIds as $key=>$value){
                $goodsData = Db::name('qt_goods')->where(['id'=>$value])->find();
                if (empty($goodsOrder)) {
                    //创建订单
                    $orderInsert = [
                        'order_no' => c_order_sn('2'),
                        'store_id' => $goodsData['store_id'],
                        'room_id' => $roomId,
                        'engineer_id' => '',
                        'create_id' => $userInfo['id'],
                        'hand_card_id' => $handCardId,
                        'total_price' => $goodsData['price'],
                        'content' => '',
                        'order_status' => '0',
                        'create_time' => time(),
                    ];
//                    try {
//                        Db::startTrans();
                        $orderId = Db::name('qt_product_order')->insertGetId($orderInsert);
                        $orderInsert['id'] = $orderId;
                        //插入子订单
                        self::saveProductOrderItem($goodsData, $orderInsert,$userInfo['id'],$handCardId,$handGrandId);
                        //处理提成记录
                        self::saveCommissionLog($orderId, $roomId);
                       // Db::commit();
//                    } catch (Exception $exception) {
//                        Db::rollback();
//                    }
                } else {
                    try {
                        Db::startTrans();
                        //插入子订单
                        $itemStatus = self::saveProductOrderItem($goodsData, $goodsOrder,$userInfo['id'],$handCardId,$handGrandId);
                        if($itemStatus['status'] == false){
                            $result['status'] = false;
                            $result['msg'] = $itemStatus['msg'];
                        }else{
                            //处理提成记录
                            self::saveCommissionLog($goodsOrder['id'], $goodsOrder['room_id']);
                            //更新总订单金额
                            Db::name('qt_product_order')->where('id', $goodsOrder['id'])->setInc('total_price', $goodsData['price']);
                            Db::commit();
                        }
                    } catch (Exception $exception) {
                        Db::rollback();
                    }
                }
            }
        }
        return ['status'=>true];

    }


    /**
     * 写入子订单
     * @param $goodsRes    提交的商品数组
     * @param $orderId     商品订单ID
     * @param $userInfo    用户详情
     * @param $saleId      技师ID
     */
    public static function saveProductOrderItem($goodsData, $orderData, $userId,$handCardId,$handGrantId)
    {
        $orderData = Db::name('qt_product_order')
            ->field('o.id,o.room_id,o.hand_card_id,hc.type as hand_type')
            ->alias('o')
            ->leftJoin('qt_hand_card hc', 'hc.id = o.hand_card_id')
            ->where('o.id', $orderData['id'])
            ->find();
        if ($orderData['hand_type'] != null) {
            //判断手牌最大商品数量
            $handCardGoodsNumber = Db::name('qt_hand_goods')
                ->where(['product_id' => $goodsData['id'], 'store_id' => $goodsData['store_id']])
                ->where("FIND_IN_SET(" . $orderData['hand_type'] . ",type)")
                ->value('number');
            if ($handCardGoodsNumber != null) {
                //判断商品是否超出数量
                $number = Db::name('qt_product_order_item')->where(['order_id' => $goodsData['id'], 'goods_id' => $goodsData['id']])->count();
                if (($number + 1) > $handCardGoodsNumber) {
                    return ['msg' => '超出最大商品数量', 'status' => false];
                }
            }
        }
        $userGroup = Db::name('qt_users')->where(['id'=>$userId])->value('group');
        if($userGroup == '1'){
            $insert['commission'] = $goodsData['engineer_rate'];
        }else{
            $insert['receiver'] = $goodsData['engineer_rate'];
        }
        $roomId = $orderData['room_id'];
        $insert['order_id'] = $orderData['id'];
        $insert['room_id'] = $roomId;
        $insert['store_id'] = $goodsData['store_id'];
        $insert['hand_card_id'] = $handCardId;
        $insert['goods_id'] = $goodsData['id'];
        $insert['goods_name'] = $goodsData['name'];
        $insert['goods_price'] = $goodsData['price'];
        $insert['goods_num'] = '1';
        $insert['goods_total_price'] = $goodsData['price'];
        $insert['create_time'] = time();
        $insert['sale_id'] = $userId;
        $insert['create_id'] = $userId;
        $insert['business_type'] = 6;
        Db::name('qt_product_order_item')->insert($insert);
        //给手牌加金额
        Db::name('qt_hand_grant')->where('id',$handGrantId)->setInc('money',$goodsData['price']);


        $secData = Db::name('qt_product_order_item')->where(['order_id' => $orderData['id']])->select();
        foreach ($secData as $key => $value) {
            //插入订单详情表
            $orderDetailInsert = [
                'store_id' => $goodsData['store_id'],
                'room_id' => $orderData['room_id'],
                'engineer_id' => '',
                'hand_card_id' => $handCardId,
                'check_out_id' => '',
                'project_id' => $value['goods_id'],
                'order_goods_id' => $value['id'],
                'create_user_id' => $userId,
                'order_type' => '2',
                'create_time' => time(),
            ];
            Db::name('qt_order_detail')->insert($orderDetailInsert);
        }
        //商品减库存
        $goodsProduct = Db::name('qt_goods_product')->where(['goods_id' => $goodsData['id']])->find();
        //有关联库存减库存
        if (!empty($goodsProduct)) {
            $stockData = json_decode($goodsProduct['product_data'], true);
            foreach ($stockData as $k => $v) {
                //[{"product_id":46,"number":"2","name":"果粒橙","unit":"瓶"}]
                $productData = Db::name('qt_product')->where(['id' => $v['product_id']])->find();
                //dump($productData);die;
                if ($productData != null) {
                    $decNumber = bcmul($value['goods_num'], $v['number']);
                    $afterNumber = bcsub($productData['stock'], $decNumber);
                    try {
                        Db::startTrans();
                        //减库存
                        Db::name('qt_product')->where(['id' => $v['product_id']])->setDec('stock', $decNumber);
                        //插入记录
                        $insert = [
                            'product_id' => $v['product_id'],
                            'store_id' => $productData['store_id'],
                            'before' => $productData['stock'],
                            'amount' => $decNumber,
                            'after' => $afterNumber,
                            'type' => '1',
                            'acter' => $userId,
                            'source' => '2',
                            'relation_id' => $value['id'],
                            'create_time' => time(),
                        ];
                        Db::name('qt_product_stock_log')->insert($insert);
                        Db::commit();
                    } catch (Exception $exception) {
                        Db::rollback();
                    }
                }
            }
            return ['msg' => '添加子订单成功', 'status' => true];
        }
        return ['msg' => '添加子订单成功', 'status' => true];
    }


    /**
     * 写提成记录表
     *
     * @param $order_id      商品订单ID
     * @param $room_id       房间ID
     */
    public static function saveCommissionLog($order_id, $room_id)
    {
        $goods_item = Db::name('qt_product_order_item')
            ->where('order_id', $order_id)->select();
        if (!empty($goods_item)) {
            $insert = [];
            foreach ($goods_item as $key => $value) {
                $checkFind = Db::name('qt_commission_log')->where(['order_project_id'=>$value['id'],'type'=>'2'])->find();
                if(empty($checkFind)){
                    $userGroup = Db::name('qt_users')->where(['id'=>$value['sale_id']])->value('group');
                    if($userGroup != null && $userGroup == '1'){
                        $userId = $value['sale_id'];
                    }else{
                        $userId = 0;
                    }
                    $insert[] = [
                        'store_id' => $value['store_id'],
                        'cashier_id' => !empty($value['sale_id']) ? $value['sale_id'] : 0,
                        'user_id' => $userId,
                        'room_id' => $room_id,
                        'money' => $value['goods_price'],
                        'commission' => $value['commission'],
                        'receiver' => $value['receiver'],
                        'product_id' => $value['goods_id'],
                        'type' => '2',
                        'created_time' => time(),
                        'is_pay' => '1',
                        'order_project_id' => $value['id'],
                    ];
                }
            }
            Db::name('qt_commission_log')->insertAll($insert);

        }
    }


    /**
     * 取消手牌删除
     * @param $orderGoodsID
     */
    public static function delAdmissionPrice($handCardId){
        $handCardData = Db::name('qt_hand_card')->where(['id'=>$handCardId])->find();
        $handGrantData = Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCardId,'status'=>'2'])->order('id desc')->find();
        $admissionTicketData = self::where("FIND_IN_SET(" . $handCardData['type'] . ",hand_cards)")->where(['store_id'=>$handCardData['store_id']])->find();
        if(empty($admissionTicketData)){
            return ['status'=>true,'msg'=>'取消成功'];
        }
        //查找取消时间
        $cancelTime = $admissionTicketData['cancel_time'] * 60;
        $endTime = $handGrantData['create_time'] + $cancelTime;
        if(time() < $endTime){
            //可以取消手牌
            $order_item = Db::name('qt_product_order_item')
                ->alias('oi')
                ->field([
                    'oi.id',
                    'oi.goods_name',
                    'oi.goods_id',
                    'oi.goods_num',
                    'oi.goods_total_price',
                    'po.room_id',
                    'po.engineer_id',
                    'r.name as room_name',
                    'oi.create_id',
                    'oi.order_id',
                    'oi.sale_id'
                ])
                ->leftJoin('qt_product_order po','po.id=oi.order_id')
                ->leftJoin('qt_room r','po.room_id=r.id')
                ->where(['oi.hand_card_id'=>$handCardId,'oi.business_type'=>'6','oi.pay_status'=>'0'])
                ->select();
            if(!empty($order_item)){
                $isPay = Db::name('qt_product_order_item')->where(['id'=>$order_item[0]['order_id'],'pay_status'=>'1'])->find();
                if($isPay != null){
                    return ['status'=>false,'msg'=>'该手牌有消费，暂时不能取消'];
                }
            }
            foreach ($order_item as $key=>$value){
                $text = '房间  '.$value['room_name']. '  '.$value['goods_name'] . '    数量    '.$value['goods_num'] . ' 退单';
//                    try{
//                        Db::startTrans();
                    //更新订单详情状态
                    Db::name('qt_order_detail')->where('order_goods_id',$value['id'])->update(['status'=>'2']);
                    //更新商品订单信息
                    Db::name('qt_product_order_item')->where('id',$value['id'])->delete();
                    //删除提成记录
                    Db::name('qt_commission_log')->where(['order_project_id'=>$value['id']])->delete();
                    //增加库存记录
                    $stockModel = new ProductOrder();
                    $stockModel::stockInc($value['goods_id'],$value['goods_num'],$value['id'],['id'=>$value['sale_id']]);
                    Db::name('qt_send_voice_msg')->insert(['content' => $text, 'type' => 1,'create_time'=>time(),'voice_type'=>2]);
//                        Db::commit();
//                    }catch (Exception $exception){
//                        Db::rollback();
//                    }
            }
            //更新发放记录
            Db::name('qt_hand_grant')->where('id',$handGrantData['id'])->update(['status'=>'5']);
            //更新手牌
            Db::name('qt_hand_card')->where('id',$handCardData['id'])->update(['status'=>'1']);
            return ['status'=>true,'msg'=>'取消成功'];
        }else{
            return ['status'=>false,'msg'=>'超出允许取消时间了'];
        }
    }


}